package com.bigevent.controller;

import com.bigevent.pojo.Result;
import com.bigevent.pojo.User;
import com.bigevent.service.UserService;
import com.bigevent.utils.JwtUtil;
import com.bigevent.utils.Md5Util;
import com.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    // 通过valication 实现参数的校验
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 查询用户
        User user = userService.findByUserName(username);
        // 判断用户是否存在
        if (user == null) {
            userService.register(username, password);
            return Result.success();
        } else {
            return Result.error("用户名已存在");
        }
    }

    // 登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 根据用户名查询用户
        User loginUser = userService.findByUserName(username);

        // 判断该用户是否存在
        if (loginUser == null) {
            return Result.error("用户名不存在");
        }

        // 判断密码是否正确
        // 加密参数中的密码
        String md5String = Md5Util.getMD5String(password);
        if (!loginUser.getPassword().equals(md5String)) {
            return Result.error("密码错误");
        }
        //生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", loginUser.getUsername());
        claims.put("id", loginUser.getId());
        // TODO
        claims.put("authority",loginUser.getAuthority());
        String token = JwtUtil.genToken(claims);
        // 把token存储到redis中
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token, token, 12, TimeUnit.HOURS);
        return Result.success(token);
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization") String token*/) {
        // 根据用户名查询用户
        /*Map<String, Object> claims = JwtUtil.parseToken(token);
        String username = (String) claims.get("username");*/
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");

        User user = userService.findByUserName(username);
        return Result.success(user);
    }


    /*
     * 更新用户详细信息
     * */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);

        return Result.success();
    }

    /*
    * 更新用户头像
    * */
    @PatchMapping("/updateAvatar")
    public Result updateUserPic(@URL String avatarUrl){
        userService.updateUserPic(avatarUrl);
        return Result.success();
    }

    /*
    * 更新用户密码
    * */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token){
        log.info("密码集合是{}",params);
        // 参数的校验
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("参数不能为空");
        } else if (!newPwd.equals(rePwd)) {
            return Result.error("两次密码不一致");
        }
        userService.updateUserPwd(params);
        // 删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}

